﻿package com.cf.core.control{
	import com.cf.core.Utils.cache;
	import com.cf.core.Utils.tools;
	import com.cf.core.events.UIEvent;
	import flash.ui.Keyboard;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.EventDispatcher;
	public class keyAction extends Sprite{
		private var G_reg:cache;
		public function get VAR():Function{return G_reg.address}
		public function get keyEvent():KeyboardEvent{return VAR('reg').event}
		public function set keyEvent(_e:KeyboardEvent):void{VAR('reg').event=_e}
		public function get KeyRule():Array{return VAR('reg').rule}
		
		public function bind(...arg):void{
			var _keyed:Boolean=false;
			var _fned:Boolean=false;
			var _arr:Array=new Array();
			for(var prop in arg){
				switch( typeof(arg[prop]) ){
					case uint: case int: case Number:
						// it should be keyCode
						_keyed=true;
					break;
					case String:
						// String.fromCharCode(e.charCode)
						// _keyed=true;
					break;
					case Function:
						// it should be the Function who want to process.
						_fned=true;
					break;
				}//case
			}//for
			if( _keyed && _fned ){
				
			}else{
				trace("keyAction bind FAIL : "+ tools.varInfo(arg) );
			}//if
		}//fn
		public function unbind():void{
			
		}//fn
		
		//
		// init
		//
		public function keyAction(){
			if (stage) {
				init();
			}else{
				addEventListener(Event.ADDED_TO_STAGE, init);
			}//if
		}//fn
		public function RELEASE(e:Event=null):void{
			try{
				stage.removeEventListener(KeyboardEvent.KEY_DOWN,	keyHandler);
				stage.removeEventListener(KeyboardEvent.KEY_UP,		keyHandler);
			}catch(e){}
			trace("keyAction : Release");
			G_reg.RELEASE();
			try{
				removeEventListener(Event.REMOVED_FROM_STAGE, RELEASE);
			}catch(e){}
		}//fn
		public function init(e:Event=null){
			try{
				removeEventListener(Event.ADDED_TO_STAGE, init);
			}catch(e){}
			G_reg=new cache();
			addEventListener(Event.REMOVED_FROM_STAGE, RELEASE);
			stage.addEventListener(KeyboardEvent.KEY_DOWN,	keyHandler);
			stage.addEventListener(KeyboardEvent.KEY_UP,	keyHandler);
			VAR('reg', Object).History = new Array();
			VAR('reg').rule = new Object();
			keyEvent = null;
			trace("KeyAction : inited on "+ stage);
		}//fn
		protected function keyHandler(e:KeyboardEvent):void{
			checkKey(e);
			switch(e.type){
				case KeyboardEvent.KEY_DOWN:
					dispatchEvent(new UIEvent(UIEvent.KEYDN) );
				break;
				case KeyboardEvent.KEY_UP:
					dispatchEvent(new UIEvent(UIEvent.KEYUP) );
				break;
			}//case
		}//fn
		protected function checkKey(e:KeyboardEvent):void{
			keyEvent = e;
			trace("keyAction : "+ keyEvent);
			
		}//fn
	}//class
}//package